<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Support\Facades\Validator;

class Controller extends BaseController
{
    use DispatchesJobs, ValidatesRequests;

    /**
     * 验证器验证
     * @param $data 需要验证的数据
     * @param $rules 需要验证的规则
     * @param $messages 验证规则发挥的错误提示
     */
    protected function checkParams($data,$rules,$messages){
        $validator = Validator::make($data,$rules,$messages);
        if($validator->fails()){
            $error = $validator->errors()->first();
            return [
                'code'=>1,
                'message'=>$error
            ];
        }else{
            return [
                'code'=>0,
                'message'=>'参数无误'
            ];
        }
    }

    //记录错误日志
    protected function logErr($code,$message,$type){
        $file = date('Ymd').'.txt';
        $filepath =  storage_path('logs/syserrs/'.$file);
        $inputText = date("H:i:s").":\n".$type.": ";
        $inputText .= json_encode([
            'code'=>$code,'message'=>$message
        ]);
        $inputText.="\n\r";
        file_put_contents($filepath,$inputText,FILE_APPEND);
    }

    //登录token生成方法
    protected function setToken($key,$expire=3600){
        $time = time();
        $data = ['key'=>$key,'expire'=>$time+$expire];
        $token = encrypt($data);
        return $token;
    }

    //交易数据签名解密
    protected function decreSign($sign,$lang='zn'){
        $signkey = 'fc473d19db504eade61ec035578a7acca37481c2';
        $str = base64_decode($sign);
        if($str){
            parse_str($str,$originData);
            $secretdata = $originData['secretdata'];
            unset($originData['secretdata']);
            $str = http_build_query($originData);
            $originSecret = md5(sha1($str.'&signkey='.$signkey));
            if($originSecret!==$secretdata){
                return [
                    'code'=>1,
                    'message'=>$this->lang['SIGN_DATA_ERR'][$lang]
                ];
            }
            if($originData['expired']<time()){
                return [
                    'code'=>1,
                    'message'=>$this->lang['SIGN_EXPIRED'][$lang]
                ];
            }
            unset($originData['expired']);
            return [
                'code'=>0,
                'data'=>$originData
            ];
        }else{
            return [
                'code'=>1,
                'message'=>$this->lang['SIGN_ERR'][$lang]
            ];
        }
    }
}
